#  daemon_launcher.rb
#
#  This file is part of myvnet.
#
#  Copyright (C) 2008  Filipe David Borba Manana,  fdmanana@gmail.com
#
#  myvnet is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  myvnet is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with myvnet.  If not, see <http://www.gnu.org/licenses/>.


require 'singleton'
require 'lib/daemon_registry'
require 'lib/daemon_dispatcher'
require 'lib/daemons/ping_daemon'
require 'lib/daemons/arp_daemon'
require 'lib/daemons/udp_echo_daemon'
require 'lib/config'
require 'lib/exceptions'
require 'lib/packet/sniffer'
require 'lib/packet/injector'


module Daemon
  
  # Registers daemons, starts the daemon dispatcher and a packet sniffer.
  #
  class Launcher
    include Singleton
    
    def initialize
      @conf = Config::Settings.instance            
      @dreg = Daemon::Registry.instance
      @ddisp = Daemon::Dispatcher.instance
      
      begin
        @packet_injector = Packet::Injector.new @conf.interface
      rescue RawSocketError => ex
        msg = "Could not create raw socket for packet injection: "
        msg << "#{ex.message}"
        $log[:stderr].fatal msg
        exit 1        
      end
                        
      begin
        @sniffer = Packet::Sniffer.new(@conf.interface, @conf.addresses, :ipv4)
      rescue SnifferError => ex
        $log[:stderr].fatal "Could not start packet sniffer: #{ex.message}"
        exit 1
      end      
      
      hwaddr = @conf.interface_hwaddress
      
      # registration of daemons
      pingd = Daemon::PingDaemon.new("PingDaemon", @packet_injector, 
                                     hwaddr, @conf.addresses)
      @dreg.register pingd
      
      arpd = Daemon::ArpDaemon.new("ArpDaemon", @packet_injector,
                                   hwaddr, @conf.addresses)
      @dreg.register arpd
      
      udpechod = Daemon::UdpEchoDaemon.new("UdpEchoDaemon", @packet_injector,
                                           hwaddr, @conf.addresses)
                                         
      @dreg.register udpechod
      #
    end
    
    
    def start
      
      begin
        @sniffer.each_packet do |packet|
          @ddisp.add_packet packet
        end
      rescue Interrupt
        # normal termination
      ensure
        @packet_injector.shutdown
      end
    end
  end  
end
